<template>
  <div class="">
    <van-nav-bar title="城市列表" left-arrow @click-left="$router.go(-1)" />
    <van-index-bar class="van-bar" :index-list="indexList">
      <van-index-anchor index="#"><em>当前城市</em></van-index-anchor>
      <van-cell :title="currentCity" />
      <van-index-anchor index="热"><em>热门城市</em></van-index-anchor>
      <van-cell
        v-for="item in hotCity"
        :key="item.value"
        :title="item.label"
        @click="chooseCity(item.label, item.value)"
      />
      <div v-for="(item, index) in otherCity" :key="index">
        <van-index-anchor :index="item.text" />
        <van-cell
          :title="ele.city"
          v-for="(ele, index) in item.cityList"
          :key="index"
          @click="chooseCity(ele.city, ele.value)"
        />
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import { getHotCity, getCityList } from '@/api/area'
export default {
  name: 'city_page',
  async created () {
    const { body } = await getHotCity()
    this.hotCity = [...body]
    this.getCity()
    this.currentCity = this.$route.query.cityName || '北京'
  },
  data () {
    return {
      hotCity: [],
      otherCity: [],
      indexList: ['#', '热'],
      currentCity: '北京',
      level: 1
    }
  },
  methods: {
    async getCity () {
      const { body } = await getCityList(this.level)
      body.sort((a, b) => {
        return a.short.localeCompare(b.short)
      })
      console.log(body)
      const res = body.reduce((prev, item) => {
        const init = item.short.substring(0, 1).toUpperCase()
        // console.log(init)
        const index = prev.findIndex(item => {
          return item.text === init
        })
        if (index === -1) {
          prev.push({
            text: init,
            cityList: [{ city: item.label, value: item.value }]
          })
        } else {
          prev[index].cityList.push({ city: item.label, value: item.value })
        }
        return prev
      }, [])
      this.otherCity = res
      res.forEach(item => {
        this.indexList.push(item.text)
      })
    },
    async chooseCity (city, cityId) {
      console.log(city, cityId)
      this.$router.push({
        path: '/layout/find',
        query: {
          city,
          cityId
        }
      })
      this.$router.push({
        path: '/layout/index',
        query: {
          city,
          cityId
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.van-bar {
  em {
    color: #999;
  }
}
/deep/.van-nav-bar__content {
  background-color: #21b97a;

  .van-nav-bar__title {
    color: #fff;
    font-size: 18px;
  }
  .van-icon-arrow-left {
    color: #fff;
  }
}
</style>
